package com.example.shopsystem.control;

import com.example.shopsystem.aop.TokenMethod;
import com.example.shopsystem.entity.User;
import com.example.shopsystem.service.GoodServiceImpl;
import com.example.shopsystem.service.OrderServiceImpl;
import com.example.shopsystem.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserRg {

    @Autowired
    UserServiceImpl userServices;
    @Autowired
    OrderServiceImpl orderServices;
    @Autowired
    GoodServiceImpl goodService;

    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        if (user.getPhone() == null || user.getPwd() == null) {//为空判断
            return Result.phoneNull(null);
        }
        if (user.getPhone().length() != 11 || user.getPwd().length() < 6) {
            return Result.phoneBad(null);//字符规则判断
        }
        if (!userServices.register(user)) {
            return Result.intFail(null);
        }
        return Result.ok(null);
    }

    @PostMapping("/signIn")
    public Result<Object> signIn(@RequestBody User user, HttpServletResponse response) {//登录
        if (user.getId() == null || user.getPwd() == null) {//为空判断
            return Result.phoneNull(null);
        }
        if (!userServices.signIn(user)) {
            return Result.pwdBad("可能你已被封号，联系管理员解封");
        }
        String type = "user";
        long exTime = System.currentTimeMillis() + 10000 * 60;
        String org = user.getId() + ";" + user.getPwd() + ";" + exTime + ";" + type;
        //生成token
        String token = TokenMethod.token(org);
        //把token放到头部
        response.setHeader("Token", token);
        return Result.ok(null);
    }

    @PostMapping("/viewGoods")
    public Result<Object> viewGoods() {//查看所有在售商品

        return Result.ok(goodService.viewGoods());
    }
}
